import java.util.concurrent.Semaphore;

public class Demo2 {
    public static void main1(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(2);

        semaphore.acquire();
        System.out.println("进行了一次P操作");
        semaphore.acquire();
        System.out.println("进行了一次P操作");
        semaphore.release();
        System.out.println("进行了一次V操作");
        semaphore.release();
        System.out.println("进行了一次V操作");
    }

    private static int sum = 0;
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                try {
                    semaphore.acquire();
                    sum++;
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                try {
                    semaphore.acquire();
                    sum++;
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("sum = " + sum);
    }
}
